<?php
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/25 0025
 * Time: 17:46
 */

/**
 * 第三方配置
 *
 * @return array
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function third_config(){
    $arr_data = [
      'cloud_baidu_ocr'=>[
        'api_key'=>'agA3tujkGuE4HbROA2qVrZyK',
        'secret_key'=>'NzUWAN4a80BDi4WC7pNbP3gjTEg9bTLA',
      ],

      //微信小程序
      'small_wechat'=>[
        'app_id'=>'wx4848cf1b4f659a5c',
        'app_secret'=>'07641f1bb9591e5bd30b985c7b573f4d',
        'url_get_openid'=>'https://api.weixin.qq.com/sns/jscode2session',
      ],

      //微信小程序
      'wechat_mini_program'=>[
        'app_id'=>'wx4848cf1b4f659a5c',
        'app_secret'=>'07641f1bb9591e5bd30b985c7b573f4d',
        'url_get_openid'=>'https://api.weixin.qq.com/sns/jscode2session',
      ],

      //微信公众号
      'wechat_official_account'=>[
        'app_id'=>'wxe32410ce2999a155',
        'app_secret'=>'e1c954e39a33b292a2c29c500fa394ba',
//        'url_get_openid'=>'xxxxxxxxxxxxxxxxxxxxxxxx',
      ],
      //
      //      //微信开放平台
      //      'wechat_open_platform'=>'',
      //
      //      //微信支付
      //      'wechat_payment'=>'',
      //
      //      //企业微信
      //      'wechat_work'=>'',
    ];

    return $arr_data;
}

////////////////////////////微信小程序

/**
 * 获取微信小程序配置
 *
 * @return mixed
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function small_wechat_congfig(){
    return third_config()['wechat_mini_program'];
}

/**
 * 对微信小程序用户加密数据的解密示例代码
 *
 * 检验数据的真实性，并且获取解密后的明文.
 *
 * @param $encryptedData string 加密的用户数据
 * @param $iv string 与用户数据一同返回的初始向量
 * @param $data string 解密后的原文
 *
 * @return array 成功0，失败返回对应的错误码
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function small_wechat_biz_data_crypt($sessionKey, $encryptedData, $iv, &$data )
	{
      $appid = third_config()['wechat_mini_program']['app_id'];

      /**
       * error code 说明.
       * <ul>

       *    <li>-41001: encodingAesKey 非法</li>
       *    <li>-41002: iv 非法</li>
       *    <li>-41003: aes 解密失败</li>
       *    <li>-41004: 解密后得到的buffer非法</li>
       *    <li>-41005: base64加密失败</li>
       *    <li>-41016: base64解密失败</li>
       * </ul>
       */

//      $sessionKey = stripslashes($sessionKey);
      if (strlen($sessionKey) != 24) {
          return hello_error('encodingAesKey 非法',[],'-41001');
      }
      $aesKey=base64_decode($sessionKey);


      if (strlen($iv) != 24) {
          return hello_error('iv 非法',[],'-41002');
      }
      $aesIV=base64_decode($iv);
      $aesCipher=base64_decode($encryptedData);
      $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
      $dataObj=json_decode( $result );
      if( $dataObj  == NULL ) {
          return hello_error('网络不好，请重新登录',[],'-41003');
//          return hello_error('aes 解密失败',[],'-41003');
      }
      if( $dataObj->watermark->appid != $appid ) {
          return hello_error('网络不好，请重新登录',[],'-41003');
//          return hello_error('aes 解密失败',[],'-41003');
      }
      $data = $result;
      return  hello_success('成功',[],0);
  }

////////////////////////////微信公众号
function wechat_official_account(){
    return third_config()['wechat_official_account'];
}
function wechat_official_account_appid(){
    return third_config()['wechat_official_account']['app_id'];
}
function wechat_official_account_secret(){
    return third_config()['wechat_official_account']['app_secret'];
}

////////////////////////////百度云

/**
 * 行驶证-图文识别
 *
 * @param string $s_img
 * @param string $s_type
 *
 * @return bool|mixed|string
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function cloud_orc_vehicle_license($s_img = '',$s_type = 'tianyan')
{
//    $s_img = base64_img();
    $arr_img = explode('base64,',$s_img);
    $s_deal_img = $arr_img[1];
    switch ($s_type)
    {
        case 'baidu_cloud':
            $res = ocr_vehicle_for_baidu($s_deal_img);
            break;
        case 'tianyan':
            $res =  ocr_vehicle_for_tianyan($s_img);
            break;

        default:
            $res = ['state'=>1,'msg'=>'未知错误'];
    }

    return $res;

}

/**
 * 百度云 图文识别获取access_token
 *
 * @return false|mixed|string
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function cloud_baidu_ocr_oauth_token()
{
    $arr_third_config = third_config();
    $url = 'https://aip.baidubce.com/oauth/2.0/token';
    $post_data['grant_type']       = 'client_credentials';
    $post_data['client_id']      = $arr_third_config['cloud_baidu_ocr']['api_key'];
    $post_data['client_secret']      = $arr_third_config['cloud_baidu_ocr']['secret_key'];
    $res = curl_post($url,$post_data);
    $res = json_decode($res,true);
    return $res;
}

/**
 * 百度云-自动识别机动车行驶证
 *
 * @param string $s_img
 *
 * @return bool|mixed|string
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function ocr_vehicle_for_baidu($s_img = '')
{
    $arr_access_token = cloud_baidu_ocr_oauth_token();
    $access_token = $arr_access_token['access_token'];
    $api = 'https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license?access_token='.$access_token;
//    $header = ['Content-Length: application/x-www-form-urlencoded'];
    $post = [
      'image' => $s_img,
      'detect_direction' => 'true',
      'accuracy' => 'normal',
      'vehicle_license_side' => 'front',
    ];
    $res = curl_post($api, $post);
    $res = json_decode($res,true);
    if($res['words_result_num'] > 0){
        $data =         $res['words_result'];
        $arr_data = [
          'plate_no'      => $data['号牌号码']['words'],
          'vin'           => $data['车辆识别代号']['words'],
          'vehicle_type'  => $data['车辆类型']['words'],
          'owner'         => $data['所有人']['words'],
          'address'       => $data['住址']['words'],
          'use_character' => $data['使用性质']['words'],
          'brand_model'   => $data['品牌型号']['words'],
          'engine_no'     => $data['发动机号码']['words'],
          'register_date' => $data['注册日期']['words'],
          'issue_date'    => $data['发证日期']['words'],
        ];
        return  hello_success('成功',$arr_data);
    }
    else {
        return hello_error($res['error_msg'],[],$res['error_code']);
    }
}

/**
 * 微信退款失败错误信息
 *
 * @param string $s_err_code
 *
 * @return string
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function wechat_refund_error_code($s_err_code = ''){
    //退款错误返回的代码
    switch ($s_err_code)
    {
        case 'SYSTEMERROR':
            $sMsg = '接口返回错误,请再次提交';
            break;
        case 'BIZERR_NEED_RETRY':
            $sMsg = '退款业务流程错误,请再次提交';
            break;
        case 'TRADE_OVERDUE':
            $sMsg = '订单已经超过退款期限';
            break;
        case 'ERROR':
            $sMsg = '业务错误';
            break;
        case 'USER_ACCOUNT_ABNORMAL':
            $sMsg = '退款请求失败';
            break;
        case 'INVALID_REQ_TOO_MUCH':
            $sMsg = '无效请求过多';
            break;
        case 'NOTENOUGH':
            $sMsg = '余额不足';
            break;
        case 'INVALID_TRANSACTIONID':
            $sMsg = '无效transaction_id8';
            break;
        case 'PARAM_ERROR':
            $sMsg = '参数错误';
            break;
        case 'APPID_NOT_EXIST':
            $sMsg = 'APPID不存在';
            break;
        case 'MCHID_NOT_EXIST':
            $sMsg = 'MCHID不存在';
            break;
        case 'REQUIRE_POST_METHOD':
            $sMsg = '请使用post方法';
            break;
        case 'SIGNERROR':
            $sMsg = '签名错误';
            break;
        case 'XML_FORMAT_ERROR':
            $sMsg = 'XML格式错误';
            break;
        case 'FREQUENCY_LIMITED':
            $sMsg = '频率限制';
            break;
        default:
            $sMsg = '退款失败';
    }

    return $sMsg;
}



